package com.mx.tool.helper.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.mx.tool.helper.IEncryp;
import com.mx.tool.util.NotifyUtil;
import com.mx.tool.util.NewStrUtil;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * @Author: 徐建鹏.
 * @create: 2021-11-16 14:43
 * @Description:
 */
public class AESEncryp implements IEncryp {

    private byte[] keys;

    @Override
    public String encrypt(String content, byte[] key) {
        try {
            String result;
            if (key != null && key.length > 0) {
                keys = key;
                result = NewStrUtil.newStringUtf8(Base64.encode(SecureUtil.aes(key).encrypt(content), false));
            } else {
                AES aes = SecureUtil.aes();
                keys = aes.getSecretKey().getEncoded();
                result = NewStrUtil.newStringUtf8(Base64.encode(aes.encrypt(content), false));
            }
            return result;
        } catch (Exception e) {
            NotifyUtil.error(e.getMessage());
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public String decrypt(String content, byte[] key) {
        if (key == null || key.length <= 0) {
            NotifyUtil.error("解密密钥要不能为空");
            throw new RuntimeException("解密密钥要不能为空");
        }
        try {
            return NewStrUtil.newStringUtf8(SecureUtil.aes(key).decrypt(Base64.decode(content.getBytes(StandardCharsets.UTF_8))));
        } catch (Exception e) {
            NotifyUtil.error(e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String encrypt(String content, String key) {
        if (StringUtils.isNotBlank(key)) {
            return encrypt(content, key.getBytes(StandardCharsets.UTF_8));
        }
        return encrypt(content, new byte[0]);
    }

    @Override
    public String decrypt(String content, String key) {
        if (StringUtils.isBlank(key)) {
            NotifyUtil.error("解密密钥要不能为空");
            throw new RuntimeException("解密密钥要不能为空");
        }
        return decrypt(content, key.getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public byte[] getKeys() {
        return keys;
    }

    @Override
    public String getKey() {
        return null;
    }
}
